#!/bin/sh

# 运行jar所在目录
javaJar="/opt"
#运行的文件名
javaJarName="springboot-admin-0.0.1-SNAPSHOT.jar"
#git 下载的项目路劲
javaCodeUrl="/opt/java/sjl-root/springboot-admin"



function killProsess(){
    #程序运行的pid
    dataline=$(ps -ef|grep $javaJarName |grep -v grep |awk '{print $2}')
    if [ ! -n "$dataline" ]; then

    echo "IS NULL PID"

    else
    kill -9 $dataline
    echo "停止java程序"$dataline

    fi
}

#更新java 代码
function updateJavaCode(){
    #项目文件地址
    cd $javaCodeUrl
    echo "开始覆盖更新本地代码"
    git fetch --all
    git reset --hard origin/master
        
    echo $(git pull) 
    echo "更新结束"
}

#maven 开始打包
function mavenPackage(){
    cd $javaCodeUrl
    echo $(mvn  clean package -D maven.test.skip=true)
    echo $javaCodeUrl"/target/"$javaJarName
    if [ ! -f $javaCodeUrl"/target/"$javaJarName ];then
        echo $javaCodeUrl"/target/"$javaJarName"文件不存在"
    else
        echo "复制"$javaJarName"到"$javaJar"目录"
        
        if [ ! -f $javaJar"/"$javaJarName ];then
            echo $javaJar"/"$javaJarName "文件不存在"
            mv ./target/$javaJarName $javaJar
        else
            rm -f $javaJar"/"$javaJarName
            mv ./target/$javaJarName $javaJar
        fi
        
    fi
}

#Start java
function startJava(){
    if [ ! -f $javaJar"/"$javaJarName ];then
        echo $javaJar"/"$javaJarName"文件不存在"
    else
        echo $javaJar"/"$javaJarName
        cd $javaJar
        nohup java   -jar $javaJar"/"$javaJarName >"/dev/null" 2>&1 &
        echo "启动java程序"$(ps -ef|grep $javaJarName |grep -v grep |awk '{print $2}')
    fi
    

}

function stop(){
    echo "stop"
	echo "----------------"
	killProsess 
    echo "----------------"
}
function restart(){
    echo "restart"
    stop
    startJava
}
function update(){
    echo "update"
    echo "---更新代码----start"
    updateJavaCode
    echo "---更新代码----end"
    echo "---mvn打包----start"
    mavenPackage
    echo "---mvn打包----start"
    restart
}


case "$1" in
	start )
		echo "****************"
		startJava
		echo "****************"
		;;
	stop )
		echo "****************"
		stop
		echo "****************"
		;;
	restart )
		echo "****************"
		restart
		echo "****************"
		;;
    update )
    echo "****************"
    update
    echo "****************"
    ;;
	* )
		echo "****************"
		echo "start stop restart update"
		echo "****************"
		;;
esac




